package com.youngjun.common.security.filter;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

class HttpServletRequestWritableWrapper extends HttpServletRequestWrapper {

    private final byte[] body;
//    private final ByteArrayInputStream inputStream;
    private final BufferedReader bufferedReader;

    HttpServletRequestWritableWrapper(HttpServletRequest request, byte[] data) {
        super(request);
        body = data;
        bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)));
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return bufferedReader;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false    ;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
            @Override
            public int read() {
                return bais.read();
            }

        };
    }

}